<template>
  <div class="ant-modal-content">
    <div class="ant-modal-body">
      <el-form>
        <el-row>
          <el-col :span="6">
            <el-form-item label="会员卡号">
              <el-select v-model="ruleForm.organId" placeholder="请选择会员卡号" :disabled="!!ruleForm.organId">
                <el-option v-for="item in suppliers" :key="item.supId" :label="item.supName" :value="item.supId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据日期:">
              <el-date-picker type="datetime" v-model="ruleForm.billDate" placeholder="选择日期与时间"
                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" clearable class="input" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据编号">
              <el-input v-model="ruleForm.number" readonly placeholder="自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="关联订单">
              <el-input v-model="ruleForm.linkNumber" style="width: 240px" suffix-icon="Search"
                v-perm:retail:retail_back:insert:associateorder="handleIconClick" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="ant-row-flex" style="display: flex; align-items: center; margin-bottom: 10px;">
              <div class="ant-col" style="margin-right: 10px">
                <el-button type="primary" class="ant-btn ant-btn-primary" @click="insertTr">
                  <el-icon class="el-icon-left">
                    <Plus />
                  </el-icon>
                  <span>插入行</span>
                </el-button>
              </div>
              <div>
                <el-button type="primary" @click="removeSelectedRows" class="ant-btn ant-btn-danger"
                  v-if="selectedRows.length > 0">
                  <el-icon class="el-icon-left">
                    <Minus />
                  </el-icon>
                  <span>移除行</span>
                </el-button>
              </div>
              <div class="ant-col" style="margin-right: 10px">
                <el-button plain>扫码录入</el-button>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-row style="padding: 5px;">
          <el-col :span="19">
            <el-table border class="my-custom-table" @selection-change="handleSelectionChange" :data="tableData"
              show-summary :summary-method="getSummaries" max-height="340">
              <el-table-column type="selection" width="30" />
              <el-table-column label="仓库" width="160">
                <template #default="{ row }">
                  <el-select v-model="row.depId" placeholder="选择仓库" @change="handleDepotChange(row.depId)">
                    <el-option v-for="warehouse in depots" :key="warehouse.id" :label="warehouse.name"
                      :value="warehouse.id" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="barcode" label="条码" width="160">
                <template #default="{ row }">
                  <el-input v-model="row.barCode">
                    <template #append>
                      <el-button v-perm:retail:retail_back:insert:materialInserts="Saleinorder" :row="row"><el-icon>
                          <Search />
                        </el-icon></el-button>
                    </template>
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column label="名称" width="160">
                <template #default="{ row }">
                  <el-input class="dashed-input" v-model="row.materialName" />
                </template>
              </el-table-column>
              <el-table-column label="规格" property="shopCode">
                <template #default="{ row }">
                  <el-input class="dashed-input" v-model="row.standard" />
                </template>
              </el-table-column>
              <el-table-column label="库存">
                <template #default="{ row }">
                  <el-input class="dashed-input" v-model="row.totalOperNumber" />
                </template>
              </el-table-column>
              <el-table-column label="单位">
                <template #default="{ row }">
                  <el-input class="dashed-input" v-model="row.commodityUnit" />
                </template>
              </el-table-column>
              <el-table-column label="数量">
                <template #default="{ row }">
                  <el-input @input="change(row)" v-model="row.operNumber" />
                </template>
              </el-table-column>
              <el-table-column label="单价">
                <template #default="{ row }">
                  <el-input @input="change(row)" v-model="row.commodityDecimal" />
                </template>
              </el-table-column>
              <el-table-column label="金额">
                <template #default="{ row }">
                  <el-input v-model="row.allPrice" />
                </template>
              </el-table-column>
              <el-table-column label="备注">
                <template #default="{ row }">
                  <el-input v-model="row.remark" />
                </template>
              </el-table-column>
            </el-table>

           
          </el-col>
          <el-col :span="1" />
          <el-col :span="4">
            <el-form-item label="单据金额" data-step="5" data-title="单据金额" data-intro="单据金额等于左侧商品的总金额"
              class="centered-form-item">
              <el-input v-model="ruleForm.invoiceAmount" class="custom-input" readonly />
            </el-form-item>

            <el-form-item label="收款金额" prop="receiveAmount" data-step="6" data-title="收款金额"
              data-intro="收款金额为收银员收取用户的实际金额" class="centered-form-item">
              <el-input v-model="ruleForm.receiveAmount" class="custom-input" />
            </el-form-item>

            <el-form-item label="找零" prop="changeAmount" data-step="7" data-title="找零" data-intro="找零等于收款金额减去实收金额"
              class="centered-form-item">
              <el-input v-model="ruleForm.changeAmount" class="custom-input" readonly />
            </el-form-item>

            <el-form-item label="收款账户：">
              <el-select v-model="ruleForm.accountId" placeholder="选择结算账户">
                <el-option v-for="item in accounts" :key="item.accId" :label="item.name" :value="item.accId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row style="margin-top: 300px;">
          <el-col :span="24" :offset="0">
            <el-form-item style="float: right">
              <el-button @click="close">取消</el-button>
              <el-button @click="submitForm(1)">保存并审核</el-button>
              <el-button type="primary" @click="submitForm(0)">保存</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
  <!-- 弹窗 -->
  <el-dialog :destroy-on-close="true" :title="title" v-model="visible" width="65%" top="15vh" style="height: 750px">
    <router-view @close="closeAdd" @saveSaleinorder="saveSaleinorder" @subdocument="subdocument"
      :data="data"></router-view>
  </el-dialog>
</template>

<script setup>
import { ref, defineEmits, onMounted, watch } from 'vue';
import router from "@/router";
import request from "@/api/request";
import { Search } from "@element-plus/icons-vue";
import { ElMessage } from 'element-plus';

let title = ref("");
let visible = ref(false);
let data = ref({});
let emits = defineEmits(["close"]);

// 会员卡信息
let suppliers = ref([]);
// 收款账户信息
const accounts = ref([{ accId: 1 }]);
// 收款类型状态
const payTypes = ref([
  { label: "现付", value: "现付" },
  { label: "预付款", value: "预付款" },
]);

let tableData = ref([{ operNumber: 0, allPrice: 0 }]);

const ruleForm = ref({
  linkNumber: '',
  organId: '',
  operTime: '',
  number: '',
  payType: payTypes.value[0]?.value || '现付', // 设置为 payTypes 的第一个选项
  accountId: '',
  invoiceAmount: 0,
  receiveAmount: 0,
  changeAmount: 0,
});
const handleIconClick = (menu) => {
  title.value = "选择零售出库";
  visible.value = true;
  router.push(menu.path);
}

// 插入一条数据
const insertTr = () => {
  tableData.value.push({
    operNumber: 0,
    allPrice: 0,
  });
};

// 查询会员信息
const findsuppliers = () => {
  request({
    url: "/basic/vendor/findSupplier3",
    method: "get",
  }).then((resp) => {
    suppliers.value = resp.data;
  });
};
findsuppliers();
const selectedDepotId = ref(null);

// 处理仓库选择变化
const handleDepotChange = (depId) => {
  selectedDepotId.value = depId;
  console.log("选中的仓库ID:", depId); // 可用于调试
};
watch(
  () => tableData.value,
  (newData) => {
    // 遍历 newData 中的每一行
    newData.forEach((row) => {
      console.log("当前行的仓库ID:", row.depId);
      // 如果当前行的 depotId 存在，则更新 selectedDepotId
      if (row.depId) {
        selectedDepotId.value = row.depId; // 更新选中的仓库ID
        console.log("更新后的仓库ID:", selectedDepotId.value); // 可用于调试
      }
    });
  },
  { deep: true } // 深度监控
);

// 查询仓库数据
const depots = ref([]);
// 查询仓库数据

const loadDepot = () => {
  request({
    url: '/depot/list',
    method: 'get'
  }).then(res => {
    depots.value = res.data;

    // 设置默认值
    if (tableData.value.length > 0 && depots.value.length > 0) {
      const defaultDepotId = depots.value[0].id; // 获取第一个仓库ID
      tableData.value.forEach(row => {
        row.depId = defaultDepotId; // 为每行设置默认的仓库ID
      });
    }
  }).catch(err => {
    console.error(err);
  });
};
loadDepot();

// const loadDepot = () => {
//   request({
//     url: '/depot/list',
//     method: 'get'
//   }).then(res => {
//     depots.value = res.data;
//     if (tableData.value.length > 0) {
//       tableData.value.forEach(row => {
//         row.depotId = depots.value.length > 0 ? depots.value[0].id : null;
//       });
//       selectedDepotId.value = defaultDepotId; // 赋值给选中仓库ID
//     }
//   }).catch(err => {
//     console.error(err);
//   });
// };
loadDepot();

// 查询结算用户
const findaccounts = () => {
  request({
    url: "/basic/account/list",
    method: "get",
  }).then((resp) => {
    accounts.value = resp.data;
    let defaultAccount = accounts.value.find(account =>account.isDefault === 1);
    if(defaultAccount){
      ruleForm.value.accountId =defaultAccount.accId;
    }
  });
};
onMounted(() => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  ruleForm.value.billDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  findaccounts();

});


// 生成单据编号
onMounted(() => {
  let currentOrderNumber = parseInt(
    localStorage.getItem("purchaseD") || "1",
    10
  );
  currentOrderNumber++;

  const prefix = "LSTH";
  const suffixLength = 11;
  const formattedSuffix = currentOrderNumber.toString().padStart(suffixLength, "0");
  ruleForm.value.number = `${prefix}${formattedSuffix}`;
  localStorage.setItem("purchaseD", currentOrderNumber.toString());
});

// 计算单据金额
const calculateInvoiceAmount = () => {
  ruleForm.value.invoiceAmount = tableData.value.reduce((total, row) => total + (row.allPrice || 0), 0);
};
// 接收并显示保存的数据
const saveSaleinorder = (selectedItems) => {
console.log("selectedItems666", selectedItems);
  tableData.value = selectedItems.map((item) => ({
    barCode: item.barCode,
    categoryName: item.categoryName,
    commodityUnit: item.commodityUnit,
    materialName: item.materialName,
    mfrs: item.mfrs,
    model: item.model,
    sku: item.sku,
    standard: item.standard,
    totalIn: item.totalIn,
    remark: item.remark,
    totalOperNumber: item.totalOperNumber,
    totalOut: item.totalOut,
    commodityDecimal: item.commodityDecimal,
    basicnumber: item.basicnumber,
    allprice: item.allprice,
    mid: item.mid,
    aid: item.aid,
    operNumber: 1,
    allPrice: 1 * item.commodityDecimal,
    depId: selectedDepotId.value
  }));
  calculateInvoiceAmount();
};

// 初始收款金额值
const initialReceiveAmount = ref(0);

// 监控单据金额 (invoiceAmount) 的变化
watch(() => ruleForm.value.invoiceAmount, (newVal) => {
  if (ruleForm.value.receiveAmount === initialReceiveAmount.value) {
    ruleForm.value.receiveAmount = newVal;
  }
});
// 监控收款金额 (receiveAmount) 的变化
watch(() => ruleForm.value.receiveAmount, (newVal) => {
  initialReceiveAmount.value = newVal;
  calculateChange(); // 计算找零
});
// 计算找零
const calculateChange = () => {
  ruleForm.value.changeAmount = Math.max(0, (ruleForm.value.receiveAmount || 0) - (ruleForm.value.invoiceAmount || 0));
};


const selectedRows = ref([]);

const handleSelectionChange = (selected) => {
  selectedRows.value = selected;
};

const removeSelectedRows = () => {
  const selectedBarcodes = selectedRows.value.map(row => row.barcode);
  tableData.value = tableData.value.filter(row => !selectedBarcodes.includes(row.barcode));
  selectedRows.value = []; // 清空选中的行
};



//接收关联订单数据
let subdocument = (items, selectedItems) => {
  console.log("items", items);
  console.log("header", selectedItems);

  // 检查 selectedItems 是否有值并赋值给 ruleForm
  if (selectedItems && selectedItems.length > 0) {
    const selectedItem = selectedItems[0]; // 获取第一个选中的项目
    // 从 selectedItem 提取信息并赋值给 ruleForm
    ruleForm.value.organId = selectedItem.erpSupplier?.supId || ''; // 供应商ID
    ruleForm.value.linkNumber = selectedItem.number || ''; // 关联单据
    ruleForm.value.accountId = selectedItem.accountId || ''; // 账户ID
    ruleForm.value.billDate = selectedItem.createTime || ''; // 单据日期
  }
  tableData.value = items.map((item) => ({
    barCode: item.barCode,
    commodityUnit: item.materialUnit,
    materialName: item.name,
    depId: item.depotId,
    sku: item.sku,
    standard: item.standard,
    remark: item.remark,
    totalOperNumber: item.totalOperNumber,
    commodityDecimal: item.unitPrice,
    basicnumber: item.basicnumber,
    allPrice: item.allPrice,
    operNumber: item.operNumber,
    linkId: item.id,
    mid: item.materialId,
    aid: item.materialExtendId,
    taxRate: item.taxRate,//税率
    taxMoney: item.taxMoney,//税额
    taxLastMoney: item.taxLastMoney//价税合计
  }));
  calculateInvoiceAmount();
};


// 使用 onMounted 生命周期钩子来设置初始日期和时间
onMounted(() => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  ruleForm.value.billDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
});




// 提交表单
const submitForm = (status) => {
  const data = {
    erpDepotHead: {
      type: "入库",
      subType: "零售退货",
      defaultNumber: ruleForm.value.number,
      number: ruleForm.value.number,
      createTime: ruleForm.value.billDate,
      operTime: ruleForm.value.billDate,
      payType: ruleForm.value.payType,
      organId: ruleForm.value.organId,
      accountId: ruleForm.value.accountId,
      remark: ruleForm.value.remark,
      backAmount: ruleForm.value.changeAmount,
      changeAmount: ruleForm.value.receiveAmount,
      linkNumber: ruleForm.value.linkNumber,
      totalPrice: tableData.value.reduce((total, row) => total + parseFloat(row.allPrice || 0), 0),
      status,
    },
    erpDepotItems: tableData.value.map((row) => ({
      depotId: row.depId,
      materialId: row.mid,
      materialExtendId: row.aid,
      materialUnit: row.commodityUnit,
      sku: row.sku,
      operNumber: row.operNumber,
      basicNumber: row.operNumber,
      unitPrice: row.commodityDecimal,
      allPrice: row.allPrice,
      remark: row.remark,

    })),
  };

  request({ url: "/retail/insert", method: "post", data, headers: { "Content-Type": "application/json" } })
    .then((res) => {
      close();
      ElMessage.success("提交成功");
    })
    .catch((err) => {
      ElMessage.error("提交失败: " + (err.message || "请稍后重试"));
    });
};

// 表格合计
const getSummaries = (param) => {
  const { data } = param;
  const sums = [];
  sums[7] = data.reduce((total, item) => total + Number(item['operNumber']), 0);
  sums[9] = data.reduce((total, item) => total + Number(item['allPrice']), 0);
  return sums;
};

// input计算绑定
const change = (row) => {
  row.allPrice = row.operNumber * row.commodityDecimal;
  calculateInvoiceAmount(); // 重新计算单据金额
}


// 弹出商品选择
const Saleinorder = (menu,p) => {
  title.value = menu.cname;
  visible.value = true;
  data.value = p;
  router.push(menu.path);
  console.log("insertData", data.value);
};

// 关闭商品选择页面
const closeAdd = () => {
  visible.value = false;
};

// 关闭添加弹窗
const close = () => {
  emits("close");
};


</script>

<style scoped>
.ant-modal-body {
  padding: 20px;
}

.custom-input {
  width: 100%;
  text-align: center;
  font-size: 20px;
  height: 40px;
  color: brown;
}
</style>
